package com.oscar.ehome.view.setview;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.bean.teamBean.UpdateBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.utils.selfdialog.CustomUpdateDialog;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.VersionUtil;
import com.oscar.ehome.view.setview.view.SetView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/7/24
 * 版本更新
 */

public class CheckUpdateManger implements SetView {

    private Activity mContext;
    SetPresenter setPresenter;
    private Integer intversion;
    private String downUrl;
    private long l;
    CustomUpdateDialog dio;
    // 是否取消更新
    private boolean cancelUpdate = false;
    String path = "";//安装路径

    //长度
    private double fileLength;
    private double currentLength;
    private String File_name = "juxingehome";// 版本名字

    // 下载中
    private static final int DOWNLOAD = 1;
    // 下载结束
    private static final int DOWNLOAD_FINISH = 2;
    // 记录进度条数量
    private int progress;
    private NotificationManager notificationManager;
    private Notification notification; //下载通知进度提示
    private NotificationCompat.Builder builder;
    private boolean flag = false; //进度框消失标示 之后发送通知
    public static boolean isUpdate = false; //是否正在更新
    String text = "";//更新说明
    String isFord = "";//是否是强制更新


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String strJson = (String) msg.obj;
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    if (Build.VERSION.SDK_INT < 26) {
                        builder.setProgress(100, progress, false);
                        builder.setContentText("下载进度:" + progress + "%");
                        notification = builder.build();
                        notificationManager.notify(1, notification);
                    } else {

                    }

                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
            }
        }
    };


    public CheckUpdateManger(Activity context) {
        this.mContext = context;
        setPresenter = new SetPresenter(this);

    }

    // 检测软件更新
    public void checkUpdate() {
        setPresenter.VersionUpdate(String.valueOf(VersionUtil.getVersionName(mContext)));
    }


    @Override
    public void VersionUpdate(UpdateBean updateBean) {
        if (updateBean != null) {
//            CommonUtils.isIndex = false;
            //服务器版本
            intversion = Integer.valueOf(updateBean.getVersion());
            //app版本
            int versionCode = VersionUtil.getVersionCode(mContext);
            l = Long.parseLong(updateBean.getSize());
            //下载地址
            downUrl = updateBean.getDownUrl();
            text = updateBean.getRemarks();
            if (updateBean.isForced() != null) {
                isFord = updateBean.isForced();
                if (intversion > versionCode) {
                    showNoticeDialog();
                } else {
                    if (CommonUtils.checkupdate == 1) {
                        ToastUtil.show(mContext, "已是最新版本");
                    }
                }
            }
        } else {
            ToastUtil.show(mContext, "已是最新版本");
        }
    }

    @Override
    public void erroy() {
        ToastUtil.show(mContext, "请求失败");
    }

    @Override
    public void erry(String result) {
        if (CommonUtils.checkupdate == 1) {
            if (result.contains("最新")) {
                ToastUtil.show(mContext, result);
            }
        }
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        if (mContext != null) {
            if (!mContext.isFinishing())
                dio = new CustomUpdateDialog(mContext);
            dio.updatemessge_text.setText(text);
            if ("1".equals(isFord)) {
                dio.cha_layout.setVisibility(View.INVISIBLE);
            } else {
                dio.cha_layout.setVisibility(View.VISIBLE);
            }
            //设置点击返回和屏幕不消失
            dio.setCanceledOnTouchOutside(false);
            dio.setCancelable(false);
            // 确定
            dio.setOnPositiveListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    // 显示下载对话框
                    notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                    if (Build.VERSION.SDK_INT >= 26) {//判读版本是否在7.0以上
                        NotificationChannel channel = new NotificationChannel("1",
                                "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
                        channel.enableLights(true);//是否在桌面icon右上角展示小红点
                        channel.setLightColor(Color.GREEN);//小红点颜色
                        channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                        notificationManager.createNotificationChannel(channel);

                        int notificationId = 0x1234;
                        Notification.Builder builder = new Notification.Builder(mContext, "1");
//设置通知显示图标、文字等
                        builder.setSmallIcon(R.mipmap.ehomelogo)
                                .setContentText("正在更新...")
                                .setAutoCancel(true);
                        notification = builder.build();
                        notificationManager.notify(notificationId, notification);

//设置下载进度条

                        downloadApk();
                        dio.dismiss();
                    } else {
                        initNotification();
                        downloadApk();
                        dio.dismiss();
                    }


                }
            });
            // 取消
            dio.setOnNetiveListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    if (progress > 0) {
                        cancelUpdate = true;
                    }
                    dio.dismiss();
                }
            });
            dio.show();
        } else {
            return;
        }
    }

    //初始化通知
    private void initNotification() {


        builder = new NotificationCompat.Builder(mContext);
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putExtra("intent", 0);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentTitle("正在更新...") //设置通知标题
                .setSmallIcon(R.mipmap.ehomelogo) //设置通知的小图标
                .setLargeIcon(BitmapFactory
                        .decodeResource(mContext.getResources(),
                                R.mipmap.ehomelogo)) //设置通知的大图标
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setContentText("下载进度:" + "0%")
                .setContentIntent(pi)
                .setProgress(100, 0, false);
        notification = builder.build();//构建通知对象


    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();

    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                flag = true;
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    final String sd = CommonUtils.getSDCardRootPath();// sd路径
                    path = sd + "/com.oscar.ehome/";
                    URL url = new URL(downUrl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小

                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    fileLength = length / 1024 / 1024;
                    File file = new File(path);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(path, File_name + ".apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    long time = System.currentTimeMillis();
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        currentLength = count;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        if (flag) {
                            //1秒 更新2次进度 非常重要 否则 系统会慢慢卡死
                            if (System.currentTimeMillis() - time > 1000) {
                                // 更新进度

                                mHandler.sendEmptyMessage(DOWNLOAD);
                                time = System.currentTimeMillis();


                            }
                        } else {
                        }
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    conn.disconnect();//断开连接
                    isUpdate = false; //设置没有更新
                    if (flag) notificationManager.cancel(1); //取消通知
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    ;

    /**
     * 安装APK文件
     */
    public void installApk() {
        File apkfile = new File(path, File_name + ".apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
            //在AndroidManifest中的android:authorities值
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.oscar.ehome.provider", apkfile);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            mContext.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setAction(android.content.Intent.ACTION_VIEW);
            mContext.startActivity(install);
        }
    }

}
